package com.maple.common.usbManger;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;

public class UsbActionBroadcastReceiver extends BroadcastReceiver {
    public UsbActionBroadcastReceiver(UsbDeviceCallBack mUsbDeviceCallBack) {
        this.mUsbDeviceCallBack = mUsbDeviceCallBack;
    }

    private UsbDeviceCallBack mUsbDeviceCallBack;

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        UsbDevice usbDevice = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
        if (UsbDeviceManager.ACTION_USB_PERMISSION.equals(action)) {
            synchronized (this) {
                if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    if (usbDevice != null&&mUsbDeviceCallBack!=null)
                        mUsbDeviceCallBack.onRequestUsbPermissionSuccess(usbDevice);
                }
                else {
                        //user choose NO for your previously popup window asking for grant perssion for this usb device
                    if (usbDevice != null&&mUsbDeviceCallBack!=null)
                        mUsbDeviceCallBack.onRequestUsbPermissionFailed(usbDevice);
                }
            }
        }
        else if(action.equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)){
            if (usbDevice != null&&mUsbDeviceCallBack!=null)
                mUsbDeviceCallBack.onUsbDeviceConnected(usbDevice);
        }
        else if(action.equals(UsbManager.ACTION_USB_DEVICE_DETACHED)){
            if (usbDevice != null&&mUsbDeviceCallBack!=null)
                mUsbDeviceCallBack.onUsbDeviceDisConnected(usbDevice);
        }

    }
}
